/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 4:14:41 PM
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Mar 31, 2012
 * Time: 8:29:44 PM
 * To change this template use File | Settings | File Templates.
 */
/***************************/

  //global vars
	var form = $("#frmData");
	var name = $("#categoryName");
    var code = $("#code");
	var nameInfo = $("#categoryNameInfo");
	var status = $("#status");
	var statusInfo = $("#statusInfo");

    var isEdit = false;

$(document).ready(function(){

	//var message = $("#message");

	//On blur
	//name.blur(validateRoleName);

	//message.keyup(validateMessage);
	//On Submitting
	form.submit(function(){
		if(validateRoleName() )
			return true
		else
			return false;
	});



    disableForm("frmData");
} );

	function validateRoleName(){
		//if it's NOT valid
		if(name.val().length < 3){
			name.addClass("errorField");
			nameInfo.text("We want Category names with more than 3 letters!");
			nameInfo.addClass("errorField");
			return false;
		}
		//if it's valid
		else{
			name.removeClass("errorField");
			nameInfo.text("");
			nameInfo.removeClass("errorField");
			return true;
		}
	}

  function clearValidate(){
     //   name.removeClass("errorField");  //crooooooooooooooooooooooooooooom
        nameInfo.text("");
        nameInfo.removeClass("errorField");
  }

//////page data  ////
var isNew = false;

//////////// data Grid /////////
var mygrid;
var timeoutHnd;
var flAuto = false;
function gridGenerator() {
    mygrid = new dhtmlXGridObject('gridbox');
    mygrid.setImagePath("images/dhtmlx/imgs/");
    mygrid.setHeader("Id,Category Name,Status,sts");
    mygrid.setInitWidths("50,400,100,20");
    mygrid.setColAlign("center,left,center,left");
    mygrid.setColSorting("server,server,server,na");
    mygrid.setColTypes("ro,ro,ro,ro");
    if (mygrid.setColspan){
       mygrid.attachEvent("onBeforeSorting", customColumnSort);
    }   

    //mygrid.enablePaging(mode,pageSize,pagesInGrp,pagingControlsContainer,showRecInfo,pagingStateContainer);
    mygrid.enablePaging(true,10, 10, "pagingArea", true, "infoArea");
   // mygrid.setPagingSkin("bricks");
    mygrid.setPagingSkin("toolbar", "dhx_skyblue");
    //mygrid.setStyle("background-color:navy;color:white; font-weight:bold;", "","color:red;", "");
    mygrid.init();
    mygrid.setSkin("dhx_skyblue"); //other skins (sbdark,gray,mt,xp,clear,modern,light,dhx_skyblue )
    mygrid.attachEvent("onBeforePageChanged", function() {
        if (!this.getRowsNum()){
            return false;
        }
        return true;
    });
    mygrid.sortField_old = mygrid.sortField;
    mygrid.sortField = function() {
        mygrid.setColSorting("str,str,str,str");
        if (customColumnSort(arguments[0]))
        mygrid.sortField_old.apply(this, arguments);
    }
    mygrid.setColumnHidden(3,true);
    mygrid.sortRows = function(col, type, order) {}
    mygrid.attachEvent("onRowSelect",doOnRowSelected);
    mygrid.attachEvent("onXLE", showLoading);
    mygrid.attachEvent("onXLS", function() {
        showLoading(true)
    });    
    mygrid.loadXML("?employee/gridEmpCategory&un=" + Date.parse(new Date()),function(){
      var myToolbar=mygrid.aToolBar;
        //myToolbar.setSkin("dhx_black");
        
   });
}

function showLoading(fl) {
    var span = document.getElementById("recfound");
    if (!span)
        return;
    if (!mygrid._serialise) {
        span.innerHTML = "<i>Loading... available in Professional Edition of dhtmlxGrid</i>";
        return;
    }
    span.style.color = "red";
    if (fl === true)
    span.innerHTML = "loading...";
    else
    span.innerHTML = "";
}

function doSearch(ev) {
    if (!flAuto)
    return;
    var elem = ev.target || ev.srcElement;
    if (timeoutHnd)
    clearTimeout(timeoutHnd);
    timeoutHnd = setTimeout(reloadGrid, 500);
}
function reloadGrid() {
    var searchCriteriaCategoryName = document.getElementById("searchCriteria.categoryName").value;
    var searchCriteriaStatus = document.getElementById("searchCriteria.status").value;
    showLoading(true);
    mygrid.clearAndLoad("?employee/gridEmpCategory&categoryName=" + searchCriteriaCategoryName + "&status=" + searchCriteriaStatus +"&orderBy=" +   window.s_col + "&direction=" + window.a_direction);
    if (window.a_direction)
    mygrid.setSortImgState(true, window.s_col, window.a_direction);
}
function enableAutosubmit(state) {
    flAuto = state;
    document.getElementById("submitButton").disabled = state;
}

function customColumnSort(ind) {
    if (ind == 4) {
        alert("Table can't be sorted by this column.");
        if (window.s_col)
        mygrid.setSortImgState(true, window.s_col, window.a_direction);
        return false;
    }
    var a_state = mygrid.getSortingState();
    window.s_col = ind;
    window.a_direction = ((a_state[1] == "des") ? "asc": "des");
   reloadGrid();
    return true;
}

function doOnRowSelected(rowID,celInd){
    clearForm("frmData");
    clearValidate();
    disableForm("frmData"); 
    document.getElementById("categoryName").value  = mygrid.cells(rowID,1).getValue();
    if(mygrid.cells(rowID,3).getValue()==1){
        document.getElementById("status").checked = true;
    }
    document.getElementById("id").value  = rowID;    
    handleDefaultButtons("gridclick");
    enableElement("btnChangPass");
    $("#messagePanel").removeClass();
    $("#messagePanel").html("" ) ;
    isNew = false;

}

function initialize(fnAfterInit) {
    clearForm("frmData");
    clearValidate();
    disableForm("frmData");
    handleDefaultButtons("load");

}
function edit(){
    enableForm("frmData");
    handleDefaultButtons("edit");
    enableElement("btnChangPass");
    isEdit=true;
}
function add(){
    initialize();
    enableForm("frmData");
    isNew = true;
    // Reset  ID
    setField("id", "");
    handleDefaultButtons("add");

}

function save(){
    if(validateRoleName() ) {
        var params = serializeForm("frmData") ;
        ajaxPost("?employee/addEmpCategory", params, function(data) {

			var response =JSON.parse(data);

			if (response.status==false) {


				return;
			}

			// Success
			//actionResponse = response;
            $("#messagePanel").removeClass();
            $("#messagePanel").addClass(response.type);
            $("#messagePanel").html(response.message ) ;
            reloadGrid();

			initialize();


		});
    }

		else
			return false;

    handleDefaultButtons("save");
}

function closePage(){
    window.location.href="?home";
}

function onLoad(){
     initialize();
     gridGenerator();
     enforcePrivileges();
}
//window.onload=doOnLoad;
onLoad();

